package com.hyc.www.test;

/**
 * @author <a href="mailto:kobe524348@gmail.com">黄钰朝</a>
 * @description
 * @date 2019-07-17 17:33
 */

/**
 * @author linxu
 * @date 2019/7/17
 * <p>
 * <p>
 * Task <Execute by Order>
 * tips:
 * 1、开三个线程，这三个线程在一个死循环中不断创建，执行。每个打印的数字的不同。
 * 2、在不使用主线程休眠的情况下来保证三个线程的顺序不变。
 * 3、效率第一、不考虑空间复杂度。同时，限制时间为15分钟。
 * 4、以下是代码模板：
 *
 * <p>
 * 测试三个线程在无限执行下，都按照顺序打印1，2，3
 * </p>
 */
public class Problem1 {

    private volatile static int state = 0;

    public static void main(String[] args) throws Exception {
        Runnable p1 = () -> {
            while (state != 0) {
            }
            //除了这句打印，其它可以修改
            System.out.println("1");
            state = 1;
        };
        Runnable p2 = () -> {
            while (state != 1){
            }
            //除了这句打印，其它可以修改
            System.out.println("2");
            state = 2;
        };
        Runnable p3 = () -> {
            while (state != 2) {
            }
            //除了这句打印，其它可以修改
            System.out.println("3");
            state = 3;
        };
        Runnable p4 = () -> {
            while (state != 3) {
            }
            //除了这句打印，其它可以修改
            System.out.println("4");
            state = 4;
        };
        Runnable p5 = () -> {
            while (state != 4) {
            }
            //除了这句打印，其它可以修改
            System.out.println("5");
            state = 5;
        };
        Runnable p6 = () -> {
            while (state != 5) {
            }
            //除了这句打印，其它可以修改
            System.out.println("6");
            state = 6;
        };
        Runnable p7 = () -> {
            while (state != 6) {
            }
            //除了这句打印，其它可以修改
            System.out.println("7");
            state = 7;
        };
        Runnable p8 = () -> {
            while (state != 7) {
            }
            //除了这句打印，其它可以修改
            System.out.println("8");
            state = 8;
        };
        Runnable p9 = () -> {
            while (state != 8) {
            }
            //除了这句打印，其它可以修改
            System.out.println("9");
            state = 0;
        };
        //keep the new order.avoid new asyn.
        while (true) {
            //这部分代码不允许修改
            Thread t1 = new Thread(p1);
            Thread t2 = new Thread(p2);
            Thread t3 = new Thread(p3);
            Thread t4 = new Thread(p4);
            Thread t5 = new Thread(p5);
            Thread t6 = new Thread(p6);
            Thread t7 = new Thread(p7);
            Thread t8 = new Thread(p8);
            Thread t9 = new Thread(p9);
            Thread.sleep(1000);
            //
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            t5.start();
            t6.start();
            t7.start();
            t8.start();
            t9.start();
            Thread.sleep(3000);
            System.err.println("************************");
        }

    }
}